package com.educate.ucenter.rpc.provide.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.educate.common.utils.cache.RedisManager;
import com.educate.common.utils.converter.ListUtils;
import com.educate.common.utils.exception.AppException;
import com.educate.common.web.BeanUtils;
import com.educate.common.web.JsonUtils;
import com.educate.ucenter.dao.AccountDao;
import com.educate.ucenter.dao.UserDao;
import com.educate.ucenter.model.bo.AccountBO;
import com.educate.ucenter.model.bo.UserBO;
import com.educate.ucenter.model.po.Account;
import com.educate.ucenter.model.po.User;
import com.educate.ucenter.rpc.api.UserService;
import com.educate.ucenter.rpc.provide.config.WxConfig;
import com.educate.ucenter.rpc.provide.entry.WxLoginRes;
import com.educate.ucenter.rpc.provide.entry.WxUserInfo;
import lombok.extern.log4j.Log4j2;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

@Log4j2
@Service(
        version = "${api.service.version}",
        application = "${dubbo.application.id}",
        protocol = "${dubbo.protocol.id}",
        registry = "${dubbo.registry.id}"
)
public class UserServiceImpl implements UserService {

    @Resource RestTemplate restTemplate;
    @Resource UserDao userDao;
    @Resource WxConfig wxConfig;
    @Resource RedisManager redisManager;
    @Resource AccountDao accountDao;

    @Override
    public void create(UserBO bo) {
        userDao.insert(bo);
    }

    @Override
    public void delete(UserBO bo) {
        userDao.delete(bo);
    }

    @Override
    public void delete(String userId) {
        userDao.deleteById(userId);
    }

    @Override
    public UserBO detail(String userId) {
        Optional<User> optional = userDao.findById(userId);
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        return new UserBO(optional.get());
    }

    @Override
    public UserBO detail(UserBO bo) {
//        return detail(bo.getOrganizationId());
        return null;
    }

    @Override
    public void update(UserBO bo) {
        Optional<User> optional = userDao.findById(bo.getUserId());
        if (!optional.isPresent()) {
            throw new AppException("不存在的实例");
        }
        BeanUtils.copyPropertiesNonEmpty(bo, optional.get());
        userDao.save(optional.get());
    }

    @Override
    public Page<UserBO> query(UserBO bo) {
        return userDao.query(bo, bo.pageable()).map(UserBO::new);
    }


    @Override
    public List<UserBO> list(UserBO bo) {
        List<User> result = userDao.findAll();
        return ListUtils.map(result, UserBO::new);
    }

    @Override
    public String wxAppletSession(UserBO bo) {
        String wxLoginResStr = restTemplate.getForObject(wxConfig.getLoginUrl(bo.getWxLoginCode()),
                String.class);
        WxLoginRes wxLoginRes = JsonUtils.readValue(wxLoginResStr, WxLoginRes.class);
        if (wxLoginRes.getErrcode() != null) {
            throw new AppException("调用wxJscode2session失败,code="
                    + wxLoginRes.getErrcode() + ",msg=" + wxLoginRes.getErrmsg());
        }
        log.info("wxLoginRes.getSession_key() = " + wxLoginRes.getSession_key());
        String sessionId = new ObjectId().toHexString();
        redisManager.setForTimeMS(getClass() + sessionId, wxLoginRes.getSession_key(), 2 * 60 * 60);
        return sessionId;
    }

    @Override
    public UserBO wxAppletLogin(AccountBO bo) {
        String wxSessionKey = redisManager.get(bo.getSessionId());
        Assert.notNull(wxSessionKey, "请先登录微信");
        String userInfo = WxConfig.wxUserDecode(bo.getEncryptedData(), wxSessionKey, bo.getIv());
        WxUserInfo wxUserInfo = JsonUtils.readValue(userInfo, WxUserInfo.class);
        Account account = accountDao.findByTypeAndOpenId(Account.TYPE_WX_APPLET, wxUserInfo.getOpenId());
        final String userId;
        if (account == null) {
            userId = new ObjectId().toHexString();
            account = new Account();
            account.setUserId(userId);
            account.setOpenId(wxUserInfo.getOpenId());
            account.setType(Account.TYPE_WX_APPLET);
            account.setCreateTime(new Date());
            accountDao.save(account);
        } else {
            userId = account.getUserId();
        }
        Optional<User> userOptional = userDao.findById(userId);
        User user = userOptional.orElseGet(new Supplier<User>() {
            @Override
            public User get() {
                User user = new User();
                user.setUserId(userId);
                user.setNickname(wxUserInfo.getNickName());
                user.setGender(wxUserInfo.getGender());
                user.setCity(wxUserInfo.getCity());
                user.setProvince(wxUserInfo.getProvince());
                user.setCountry(wxUserInfo.getCountry());
                user.setAvatar(wxUserInfo.getAvatarUrl());
                user.setCreateTime(new Date());
                user.setLocked(0);
                return user;
            }
        });
        user.setLastLoginTime(new Date());
        userDao.save(user);
        return new UserBO(user);
    }

}
